/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.portalcenter.domain.action.menu;

import cn.hallele.mc.sdk.portalcenter.common.enums.MenuTypeEnum;
import cn.hallele.ms.portalcenter.domain.das.MenuDEDas;
import cn.hallele.ms.portalcenter.domain.das.RoleDEDas;
import cn.hallele.ms.portalcenter.domain.das.RoleMenuDEDas;
import cn.hallele.ms.portalcenter.domain.domain.MenuDomain;
import cn.hallele.ms.portalcenter.domain.domain.MenuQueryDomain;
import cn.hallele.ms.portalcenter.domain.domain.RoleDomain;
import cn.hallele.ms.portalcenter.domain.domain.RoleMenuDomain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * hallele_ms_portalcenter
 *
 * @author anle5
 * @since 2024/10/6 13:54
 */
@Slf4j
@Service
public class MenuDomainService {
    @Autowired
    private RoleDEDas roleDEDas;

    @Autowired
    private RoleMenuDEDas roleMenuDEDas;

    @Autowired
    private MenuDEDas menuDEDas;

    /**
     * 通过roleCode查询菜单
     *
     * @param roleCodes roleCode集合
     * @param types     菜单类型
     * @return roles
     */
    public List<MenuDomain> findByRoleCodeIn(Collection<String> roleCodes, List<MenuTypeEnum> types) {
        List<RoleDomain> roleDomains = roleDEDas.findByCodeIn(roleCodes);
        if (roleDomains.isEmpty()) {
            return new ArrayList<>(0);
        }

        List<RoleMenuDomain> roleMenuDomains = roleMenuDEDas.findByRoleIdIn(roleDomains.stream()
                .map(RoleDomain::getId)
                .collect(Collectors.toSet()));
        if (roleMenuDomains.isEmpty()) {
            return new ArrayList<>(0);
        }

        return menuDEDas.findByIdInAndTypeIn(roleMenuDomains.stream()
                .map(RoleMenuDomain::getMenuId)
                .collect(Collectors.toSet()), types);
    }

    /**
     * 通过roleCode查询菜单
     *
     * @param roleCodes roleCode集合
     * @return roles
     */
    public List<MenuDomain> findByRoleCodeIn(Collection<String> roleCodes) {
        return findByRoleCodeIn(roleCodes, Arrays.stream(MenuTypeEnum.values()).toList());
    }

    /**
     * 获取 菜单列表
     *
     * @param condition 查询条件
     * @return 系统菜单
     */
    public List<MenuDomain> getMenus(MenuQueryDomain condition) {
        return menuDEDas.findAll(MenuDomain.builder().title(condition.getTitle()).perm(condition.getPerm()).build(),
                1,
                Integer.MAX_VALUE);
    }
}
